package aiyunjian

import (
	"context"
	"fmt"
	"go-api/internal/svc"
	"gorm.io/gorm"
	"time"
)

const (
	workerPoolSize       = 1000 // 并发工作协程数
	batchSize            = 500  // 批量处理数量
	maxRetries           = 3    // 最大重试次数
	lockExpiration       = 2 * time.Minute
	statusWordInit       = 0
	statusWordComplete   = 1
	statusGeneratingFail = 22
)

type WorkerPool struct {
	maxWorkers int
	taskChan   chan func()
}

func NewWorkerPool(maxWorkers int) *WorkerPool {
	pool := &WorkerPool{
		maxWorkers: maxWorkers,
		taskChan:   make(chan func(), 1e6), // 百万级缓冲
	}
	for i := 0; i < maxWorkers; i++ {
		go pool.worker()
	}
	return pool
}

func (p *WorkerPool) Submit(task func()) {
	p.taskChan <- task
}

func (p *WorkerPool) worker() {
	for task := range p.taskChan {
		task()
	}
}

type TemplateVideoInfo struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	db     *gorm.DB
	pool   *WorkerPool
}

// Register 注册定时任务，这里改为启动监听 Redis 队列的协程
func (c *TemplateVideoInfo) Register() {
	go c.RunWordSearchJobFromQueue() // 启动监听 Redis 队列的协程
}

// RunWordSearchJobFromQueue 从 Redis 队列中获取任务并处理
func (c *TemplateVideoInfo) RunWordSearchJobFromQueue() {

}

// 公共方法
func (c *TemplateVideoInfo) acquireLock(lockKey string) bool {
	return c.svcCtx.RedisClient.SetNX(c.ctx,
		fmt.Sprintf("cron_lock:%s", lockKey),
		1,
		4*time.Minute).Val()
}
